package org.grow.cooldown.ScoreModule;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;


@Service
public class LogoutIntercepter implements HandlerInterceptor {
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie credential = null;
        for (Cookie cookie : request.getCookies()) {
            if (cookie.getName().equals(LoginIntercepter.redisId)){
                credential = cookie;
            }
        }
        if (credential ==null )
            throw new LoginIntercepter.LoginExcpt(1010,
                    "no cookie no credential no logout");
        String key = credential.getValue();
        System.out.println(key);
        Object o =redisTemplate.opsForValue().get(key);
        if (o == null) throw new LoginIntercepter.LoginExcpt(1011,
                "redis miss this key ,maybe session expired");
        Map<String, Object> userinfo = (Map<String, Object>) o;
        System.out.println("试图退出登录 ："+userinfo);
        Boolean r =redisTemplate.delete(key);
        if (!r) throw new LoginIntercepter.LoginExcpt(1012,
                "退出登录失败");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
}
